<template>
  <page-body bgImg=' ' safeAreaLeft>
    <view class="address pages font-B ">
      <nav-bar :title='title' titleColor='#00374D'>
        <view v-if="id" slot="right" class="font-B font-14" style="color: red;" @tap='delAddress'>删除</view>
      </nav-bar>
      <view class="margin-t7 c-b-fff">
        <view class="address-item jh-align-center">
          <view class="address-item-label font-B c-999 font-12">
            收货人
          </view>
          <input class="address-input font-12 c-333 font-B jh-flex-item" v-model="form.consignee" placeholder="请输入收货人名称" />
        </view>
        <view class="address-item jh-align-center">
          <view class="address-item-label font-B c-999 font-12">
            手机号码
          </view>
          <view class="jh-flex-center padding-r10">
            <view class="font-12 font-B padding-r10" style="color: grey;">
              +86 
            </view>
            <image :src="ossDomain + '/cell-icon-right.png'" style="width: 6px;height: 12px;display: block;"></image>
          </view>
          <input class="address-input font-12 c-333 font-B jh-flex-item" v-model="form.mobile" type="number" maxlength="11" placeholder="请输入收货人手机号码" />
        </view>
        <picker mode="multiSelector" :range="region" range-key='region_name' :value="pickerValue" @columnchange='columnchange' @change='change'>
          <view class="address-item jh-align-center">
            <view class="address-item-label font-B c-999 font-12">
              所在地区
            </view>
            <input class="address-input font-12 c-333 font-B jh-flex-item" :value="form.region" disabled placeholder="省、市、区、街道" />
          </view>
        </picker>
        <view class="address-item jh-align-center">
          <view class="address-item-label font-B c-999 font-12">
            详细地址
          </view>
          <input class="address-input font-12 c-333 font-B jh-flex-item" v-model="form.address" placeholder="请输入详细地址" />
        </view>
        <view class="address-item jh-align-center" style="border-bottom: 0;">
          <view class="font-B c-333 font-12 padding-r20">
            设为默认收货地址
          </view>
          <switch @change='switchChange' :checked='form.is_default' color="#009183" style="transform: scale(.6);"/>
        </view>
      </view>
      <view class="jh-flex-center c-b-fff font-B c-00374D font-14 margin-t10" style="height: 43px;border-radius: 1px;" @tap="save">
        保存
      </view>
    </view>
    <backBtn></backBtn>
  </page-body>
</template>

<script>
  import {
    mapState
  } from 'vuex'
  import backBtn from '@/components/back-btn/back'
  export default {
    components: {
      backBtn
    },
    data() {
      return {
        ossDomain: uni.ossDomain,
        title: '编辑地址',
        regionList: {},
        id: '',
        form: {
          consignee: '', // 收货人
          region_list: [], // 省市区code
          address: '', // 详细地址
          mobile: '', // 联系电话
          is_default: false, // 是否默认地址
          user_id: '', // 用户Id
          region: '', // 所在地区
        },
        pickerValue: [0,0,0]
      }
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo,
      }),
      region () {
        let province = this.regionList[1] || []
        
        let cityIndex = 0
        try{
          cityIndex = this.regionList[1][this.pickerValue[0]].region_id
        }catch(e){ }
        let city = this.regionList[cityIndex] || []
        
        let districtIndex = 0
        try{
          districtIndex = this.regionList[cityIndex][this.pickerValue[1]].region_id
        }catch(e){ }
        let district = this.regionList[districtIndex] || []
        
        if (!province.length) {
          return []
        } else if (!city.length) {
          return [province]
        } else if (!district.length) {
          return [province,city]
        } else {
          return [province,city,district]
        }
      },
    },
    onLoad({id}) {
      this.id = id || ''
      this.getRegionList()
      if (this.id) {
        this.getUserAddressList()
      }
    },
    methods: {
      getUserAddressList () {
        this.$http.getUserAddressList().then(res => {
          console.log(res);
          let item = res.data.find(e => {
            e.is_default = Boolean(e.is_default)
            e.mobile = Number(e.mobile)
            return e.user_address_id == this.id
          })
          this.form = Object.assign(this.form,item)
        })
      },
      getRegionList () {
        let obj = {
          region_id: 1
        }
        uni.showLoading()
        this.$http.getRegionList(obj).then(res => {
          let data = res.data
          let parent = {}
          for (let i = 0; i < data.length; i++) {
            let item = data[i]
            if (!parent[item.parent_id]) {
              parent[item.parent_id] = []
            }
            parent[item.parent_id].push(item)
          }
          this.regionList = parent
          console.log(parent);
          uni.hideLoading()
        })
      },
      columnchange (e) {
        let detail = e.detail
        if (detail.column == 0) {
          this.pickerValue = [detail.value, 0, 0]
        } else if (detail.column == 1) {
          this.pickerValue = [this.pickerValue[0], detail.value, 0]
        } else {
          this.$set(this.pickerValue, detail.column, detail.value)
        }
      },
      change (e) {
        let indexArr = e.detail.value
        let province = this.region[0][indexArr[0]]
        let city = this.region[1][indexArr[1]]
        let district = this.region[2][indexArr[2]]
        let region_list = [province.region_id, city.region_id, district.region_id]
        this.$set(this.form, 'region_list', region_list)
        let region = `${province.region_name} ${city.region_name} ${district.region_name}`
        this.$set(this.form, 'region', region)
      },
      switchChange (e) {
        this.$set(this.form, 'is_default', e.detail.value)
      },
      save () {
        this.form.user_id = this.userInfo.user.user_id
        if (this.id) {
          this.form.user_address_id = this.id
        }
        let err = ''
        let {consignee,region,address,mobile} = this.form
        if (!consignee) {
          err = '请输入收货人名称'
        } else if(!mobile) {
          err = '请输入收货人手机号码'
        } else if(!region) {
          err = '请选择省、市、区、街道'
        } else if(!address) {
          err = '请输入收货详细地址'
        }
        if(err) {
          return uni.showToast({
            title: err,
            icon: 'none'
          })
        }
        let act = this.$http.addUserAddressItem
        if (this.id) {
          act = this.$http.setUserAddressItem
        }
        uni.showLoading({
          mask: true
        })
        act(this.form).then(res => {
          console.log(res);
          uni.showToast({
            title: `${this.id ? '修改' : '新增'}地址成功`
          })
          setTimeout(()=>{
            uni.navigateBack()
          },2000)
        })
      },
      delAddress () {
        uni.showModal({
          title: '提示',
          content: '是否要删除收货地址',
          success:(e) => {
            console.log(e);
            if (e.confirm) {
              let obj = {
                user_address_id: [this.id]
              }
              uni.showLoading({
                mask: true
              })
              this.$http.delUserAddressList(obj).then(res => {
                uni.showToast({
                  title: `删除地址成功`
                })
                setTimeout(()=>{
                  uni.navigateBack()
                },2000)
              })
            }
          }
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .pages{
    width: 100%;
    height: 100vh;
    padding:0 30px;
    box-sizing: border-box;
  }
  .address{
    &-item{
      padding:0 20px;
      height: 40px;
      border-bottom: 1px solid rgba($color: #CFCFCF, $alpha: .6);
      &-label{
        width: 73px;
      }
      &-input{
        height: 100%;
      }
    }
    &-tag{
      padding: 2px;
      border: 1px solid #FF8125;
      border-radius: 1px;
      color: #FF8125;
    }
  }
</style>
